<?php
/**
 * Created by PhpStorm.
 * 商品价格牌处理服务
 * User: Min
 * Date: 2018/1/29
 * Time: 19:38
 */

namespace SDXApi\Service;

use Think\Log;


/**
 * Class GoodsPriceTagService
 * @package SDXApi\Service
 */
class GoodsPriceTagService {
    /**
     * @var string
     */
    protected $url = 'http://47.100.50.216:35005/Market/marketController/updateService.do';

    /**
     * @var string
     */
    protected $token = '2de37b56318dc8f189acda8894f35c2a';

    /**
     * @var string
     */
    protected $operator = 'sdx_admin';

    /**
     * 店铺编码 顶级店铺为空
     * @var string
     */
    protected $storeCode = '';

    /**
     * @var string
     */
    protected $field = 'g.goods_id,
                        g.goods_sn,
                        g.goods_name,
                        g.promote_price,
                        g.promote_start_date,
                        g.promote_end_date,
                        g.promote_user_rank,
                        g.shop_price,
                        g.promote_user_rank,
                        g.spec_unit,
                        g.spec_value,
                        g.origin,
                        g.goods_weight,
                        p.user_price,
                        v.user_price as meber_price,
                        b.brand_name
                        ';

    /**
     * 导入多个商品
     * @author Min
     * @return bool
     */
    public function improtGoodsList(){
        if($_SERVER['HTTP_HOST'] != 'api.shidexian.com'){
            return false;
        }

        $goods_list = $this->getGoodsList();

        if($goods_list){
            $goods = $this->goodsPriceHandling($goods_list);
            return $this->updateGoods($goods);

        }else{
            returnApiError('数据不存在');
        }

    }

    /**
     * 导入商品
     * @author Min
     * @param $goods_id
     * @return bool
     */
    public function improtGoods($goods_id){
        set_time_limit(0);
        if($_SERVER['HTTP_HOST'] != 'api.shidexian.com'){
            return false;
        }

        if(empty($goods_id)){
            return false;
        }

        $goods = $this->getGoods($goods_id);
        if($goods){
            return $this->updateGoods($this->goodsPriceHandling($goods));
        }
    }

    /**
     * 获取商品列表
     * @author Min
     * @return mixed
     */
    protected function getGoodsList(){
        $where = array(
            'g.is_delete' => 0,
            //'g.is_on_sale' => 1,
        );

        return  M('goods')
                ->alias('g')
                ->join('left join sdx_member_price as p on g.goods_id=p.goods_id and p.user_rank=1')
                ->join('left join sdx_member_price as v on g.goods_id=v.goods_id and v.user_rank=2')
                ->join('left join sdx_brand as b on g.brand_id=b.brand_id')
                ->field($this->field)
                ->where($where)
                ->order('goods_id desc')
                ->select();
    }

    /**
     * 获取商品详情
     * @author Min
     * @param $goods_id
     * @return mixed
     */
    protected function getGoods($goods_id){
        $where['g.goods_id'] = array('in', $goods_id);

        return  M('goods')
            ->alias('g')
            ->join('left join sdx_member_price as p on g.goods_id=p.goods_id and p.user_rank=1')
            ->join('left join sdx_member_price as v on g.goods_id=v.goods_id and v.user_rank=2')
            ->join('left join sdx_brand as b on g.brand_id=b.brand_id')
            ->field($this->field)
            ->where($where)
            ->select();
    }

    /**
     * 商品价格处理
     * @author Min
     * @param $goods_list
     * @return mixed
     */
    protected function goodsPriceHandling($goods_list){
        $time = gmtime();
        foreach ($goods_list as $key=>$val){
            $promote_price = '';
            $promote_start_date = '';
            $promote_end_date = '';
            if($val['promote_user_rank'] == 3 && $time < $val['promote_end_date'] && $val['promote_price']){
                $promote_price = $val['promote_price'];
                $promote_start_date = local_date('Y-m-d H:i:s', $val['promote_start_date']);
                $promote_end_date = local_date('Y-m-d H:i:s', $val['promote_end_date']);
            }

            $goods_list[$key]['promote_price'] = $promote_price;
            $goods_list[$key]['promote_start_date'] = $promote_start_date;
            $goods_list[$key]['promote_end_date'] = $promote_end_date;
            $goods_list[$key]['goods_price'] = $val['user_price'] ? $val['user_price'] : $val['shop_price'];
        }
        return $goods_list;
    }

    /**
     * 商品导入、修改
     * @author Min
     * @param $goods_list
     * @return bool
     */
    protected function updateGoods($goods_list){
        $goods = array();
        foreach ($goods_list as $key=>$val){
            $goods[$key] = array(
                'storeCode' => $this->storeCode, //店铺编码
                'goodsName' => htmlspecialchars($val['goods_name']), //商品名称
                'goodsPrice' => $val['goods_price'], //商品价格
                'memberPrice' => $val['meber_price'], //会员价
                'promotionPrice' => $val['promote_price'], //促销价
                'discountPrice' => '', //折扣价
                'goodsCode' => $val['goods_sn'], //商品编码
                'goodsBarcode' => $val['goods_sn'], //商品条形码
                'goodsQrcode' => $val['goods_sn'], //商品二维码显示内容
                'goodsSpecifications' => $this->getGoodsSpecifications($val['goods_weight'], $val['spec_value'], $val['spec_unit']), //商品规格
                'goodsPlace' => $val['origin'], //商品产地
                'unit' => $val['spec_unit'], //单位
                'number' => '', //货号
                'alcoholicStrength' => '', //酒精度
                'level' => '', //等级
                'startTime' => $val['promote_start_date'], //活动开始时间
                'endTime' => $val['promote_end_date'], //活动结束时间
                'stock' => '', //库存
                'remarkOne' => '', //备注一
                'remarkTwo' => '', //备注二
                'remarkThree' => '扫码购物', //备注三
                'brand' => htmlspecialchars($val['brand_name']) //品牌
            );
        }

        $this->write_log(json_encode($goods), 'GoodsPriceTagService');

        $data = $this->getXmlData($goods, 'goodsInfo', 'updateGoodsInfoFormERP');
        return $this->xmlToArray($this->postXml($data));
    }

    /**
     * @author Min
     * @param $goods_weight
     * @param $spec_value
     * @param $spec_unit
     * @return string
     */
    protected function getGoodsSpecifications($goods_weight, $spec_value, $spec_unit){
        if($goods_weight > 0){
            if($goods_weight >= 1){
                $spec = ($goods_weight*1000/1000) . '千克';
            }else{
                $spec = $goods_weight*1000 . '克';
            }

            if($spec_unit != 'g' && $spec_unit != 'kg'){
                $spec .= '/'.($spec_value > 1 ? $spec_value : '') . $spec_unit;
            }

        }else{
            $spec = $spec_value ? ($spec_value.$spec_unit) : '';
        }

        return $spec;

    }


    /**
     * 增加修改门店
     * @author Min
     * @return bool
     */
    public function updateStore(){
        $data = array(
            array(
                'storeName' => '天河店1',
                'storeCode' => '123456781'
            )
        );

        $data = $this->getXmlData($data, 'storeInfo', 'updateShopInfoFormERP');
        return $this->xmlToArray($this->postXml($data));
    }

    /**
     * 组装Xml数据
     * @author Min
     * @param $data
     * @param $key
     * @param $action
     * @return string
     */
    protected function getXmlData($data, $key, $action){
        $xml = "<request>
                    <action>{$action}</action>
                    <operator>{$this->operator}</operator>
                    <operatorTime>".date('Y-m-d H:i:s')."</operatorTime>
                    <token>{$this->token}</token>
                    {$this->arrayToXml($data, $key)}
                </request>";
        return $xml;
    }

    /**
     * post提交xml
     * @author Min
     * @param $data
     * @return mixed
     */
    protected function postXml($data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$this->url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /**
     * 数组转XML
     * @author Min
     * @param $arr
     * @param $k
     * @return string
     */
    public function arrayToXml($arr, $k){
        $xml = "";
        foreach ($arr as $key=>$val){
            if(is_array($val)){
                $xml.="<".$k.">".$this->arrayToXml($val, $k)."</".$k.">";
            }else{
                $xml.="<".$key.">".$val."</".$key.">";
            }
        }
        return $xml;
    }

    /**
     * XMl转数组
     * @author Min
     * @param $xml
     * @return mixed
     */
    protected function xmlToArray($xml){
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $val = json_decode(json_encode($xmlstring),true);
        return $val;
    }

    /**
     * @param $message
     * @param $filename
     */
    public function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }

}